package com.xiaoyu.dao;

import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

public class BaseDao {
    private static String driver = null;
    private static String url = null;
    private static String username = null;
    private static String password = null;

    static{
        try{
            InputStream in = BaseDao.class.getClassLoader().getResourceAsStream("db.properties");
            Properties properties = new Properties();
            properties.load(in);
            driver = properties.getProperty("driver");
            url = properties.getProperty("url");
            username = properties.getProperty("username");
            password = properties.getProperty("password");
            // 驱动只要加载一次
            Class.forName(driver);
        }catch (IOException | ClassNotFoundException e){
            e.printStackTrace();
        }
    }

    // 获取连接
    public static Connection getConnection() throws SQLException {
        return DriverManager.getConnection(url, username, password);
    }

    //公共查询方法
    public static ResultSet execute(Connection conn, String sql, Object[] params, ResultSet rs, PreparedStatement pst) throws SQLException {
        pst = conn.prepareStatement(sql);
        for (int i = 0; i < params.length; i++) {
            pst.setObject(i+1,params[i]);
        }
        rs = pst.executeQuery();
        return rs;
    }


    //公共增删改查方法
    public static int execute(Connection conn, String sql, Object[] params, PreparedStatement pst) throws SQLException {
        pst = conn.prepareStatement(sql);
        for (int i = 0; i < params.length; i++) {
            pst.setObject(i+1,params[i]);
        }
        int updateRows= pst.executeUpdate();
        return updateRows;
    }

    // 释放连接资源
    public static boolean release(Connection conn, PreparedStatement pst, ResultSet rs){
        boolean flag = true;
        if(rs!=null){
            try {
                rs.close();
                rs = null;
            } catch (SQLException e) {
                e.printStackTrace();
                flag = false;
            }
        }
        if(pst!=null){
            try {
                pst.close();
                pst = null;
            } catch (SQLException e) {
                e.printStackTrace();
                flag = false;
            }
        }
        if(conn!=null){
            try {
                conn.close();
                conn = null;
            } catch (SQLException e) {
                e.printStackTrace();
                flag = false;
            }
        }
        return flag;
    }
}
